#include <my_header.h>
// 自旋锁：当线程不满足条件时，**线程会一直循环(一直占用CPU),  直到条件成立。**

/* Usage: ./18_spinlock */
pthread_spinlock_t mSpinlock;
void *threadFunc(void *arg)
{
    sleep(1);
    pthread_spin_lock(&mSpinlock);
    printf("child get lock \n");
    pthread_spin_unlock(&mSpinlock);
    return NULL;
}
int main(void){                                  
    // 初始化自旋锁
    // 第二个参数：PTHREAD_PROCESS_PRIVATE；同一进程不同线程
    // PTHREAD_PROCESS_SHARED:不同进程(锁变量处在共享区域内)
    pthread_spin_init(&mSpinlock, PTHREAD_PROCESS_PRIVATE);

    pthread_t tid;
    int ret_create = pthread_create(&tid, NULL, threadFunc, NULL);
    THREAD_ERROR_CHECK(ret_create, "pthread_create");

    // 上自旋锁
    pthread_spin_lock(&mSpinlock);
    printf("main get lock\n");
    sleep(5);
    pthread_spin_unlock(&mSpinlock);

    int ret_join = pthread_join(tid,NULL);
    THREAD_ERROR_CHECK(ret_join, "pthread_join");

    pthread_spin_destroy(&mSpinlock);
    return 0;
}


